connection.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. from __future__ import absolute_import
  2. import socket
  3. from .wait import NoWayToWaitForSocketError, wait_for_read
  4. from ..contrib import _appengine_environ
  5. def is_connection_dropped(conn): # Platform-specific
  6. """
  7. Returns True if the connection is dropped and should be closed.
  8. :param conn:
  9. :class:`httplib.HTTPConnection` object.
  10. Note: For platforms like AppEngine, this will always return ``False`` to
  11. let the platform handle connection recycling transparently for us.
  12. """
  13. sock = getattr(conn, "sock", False)
  14. if sock is False: # Platform-specific: AppEngine
  15. return False
  16. if sock is None: # Connection already closed (such as by httplib).
  17. return True
  18. try:
  19. # Returns True if readable, which here means it's been dropped
  20. return wait_for_read(sock, timeout=0.0)
  21. except NoWayToWaitForSocketError: # Platform-specific: AppEngine
  22. return False
  23. # This function is copied from socket.py in the Python 2.7 standard
  24. # library test suite. Added to its signature is only `socket_options`.
  25. # One additional modification is that we avoid binding to IPv6 servers
  26. # discovered in DNS if the system doesn't have IPv6 functionality.
  27. def create_connection(
  28. address,
  29. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  30. source_address=None,
  31. socket_options=None,
  32. ):
  33. """Connect to *address* and return the socket object.
  34. Convenience function. Connect to *address* (a 2-tuple ``(host,
  35. port)``) and return the socket object. Passing the optional
  36. *timeout* parameter will set the timeout on the socket instance
  37. before attempting to connect. If no *timeout* is supplied, the
  38. global default timeout setting returned by :func:`getdefaulttimeout`
  39. is used. If *source_address* is set it must be a tuple of (host, port)
  40. for the socket to bind as a source address before making the connection.
  41. An host of '' or port 0 tells the OS to use the default.
  42. """
  43. host, port = address
  44. if host.startswith("["):
  45. host = host.strip("[]")
  46. err = None
  47. # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  48. # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  49. # The original create_connection function always returns all records.
  50. family = allowed_gai_family()
  51. for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  52. af, socktype, proto, canonname, sa = res
  53. sock = None
  54. try:
  55. sock = socket.socket(af, socktype, proto)
  56. # If provided, set socket level options before connecting.
  57. _set_socket_options(sock, socket_options)
  58. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  59. sock.settimeout(timeout)
  60. if source_address:
  61. sock.bind(source_address)
  62. sock.connect(sa)
  63. return sock
  64. except socket.error as e:
  65. err = e
  66. if sock is not None:
  67. sock.close()
  68. sock = None
  69. if err is not None:
  70. raise err
  71. raise socket.error("getaddrinfo returns an empty list")
  72. def _set_socket_options(sock, options):
  73. if options is None:
  74. return
  75. for opt in options:
  76. sock.setsockopt(*opt)
  77. def allowed_gai_family():
  78. """This function is designed to work in the context of
  79. getaddrinfo, where family=socket.AF_UNSPEC is the default and
  80. will perform a DNS search for both IPv6 and IPv4 records."""
  81. family = socket.AF_INET
  82. if HAS_IPV6:
  83. family = socket.AF_UNSPEC
  84. return family
  85. def _has_ipv6(host):
  86. """ Returns True if the system can bind an IPv6 address. """
  87. sock = None
  88. has_ipv6 = False
  89. # App Engine doesn't support IPV6 sockets and actually has a quota on the
  90. # number of sockets that can be used, so just early out here instead of
  91. # creating a socket needlessly.
  92. # See https://github.com/urllib3/urllib3/issues/1446
  93. if _appengine_environ.is_appengine_sandbox():
  94. return False
  95. if socket.has_ipv6:
  96. # has_ipv6 returns true if cPython was compiled with IPv6 support.
  97. # It does not tell us if the system has IPv6 support enabled. To
  98. # determine that we must bind to an IPv6 address.
  99. # https://github.com/urllib3/urllib3/pull/611
  100. # https://bugs.python.org/issue658327
  101. try:
  102. sock = socket.socket(socket.AF_INET6)
  103. sock.bind((host, 0))
  104. has_ipv6 = True
  105. except Exception:
  106. pass
  107. if sock:
  108. sock.close()
  109. return has_ipv6
  110. HAS_IPV6 = _has_ipv6("::1")